package com.abbas.smartCity.retroft

import com.abbas.smartCity.bean.NetBean
import android.widget.Toast
import com.abbas.smartCity.App
import com.abbas.smartCity.util.Issues
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 * @see https://gitee.com/abbasspace/smart-city-2023-2-8/issues/I6WET9
 * @since 23/04/17
 * 对错误的统一处理
 *
 * @param <T> 请求的数据类型</T>
 */
@Issues("这才是正常的网络封装")
abstract class ICallback2<T> : Callback<NetBean<T>> {
    override fun onResponse(call: Call<NetBean<T>>, response: Response<NetBean<T>>) {
        App.getHandler().post {
            if (!response.isSuccessful) {
                onServerError()
            } else {
                response.body()?.let {
                    if (it.code in 200..299) {
                        onSuccess(call, it)
                    } else {
                        onRequestError(call, it.msg)
                    }
                } ?: onRequestError(call, "响应体为空")
            }
        }
    }

    override fun onFailure(call: Call<NetBean<T>>, throwable: Throwable) {
        onServerError()
    }

    /**
     * 数据访问成功后的回调
     *
     * @param call Call
     * @param data 数据
     */
    abstract fun onSuccess(call: Call<NetBean<T>>, data: NetBean<T>)

    open fun onServerError() {
        Toast.makeText(App.getContext(), "网络出现问题，请检查网络", Toast.LENGTH_SHORT).show()
    }

    open fun onRequestError(call: Call<NetBean<T>>, msg: String) {
        Toast.makeText(App.getContext(), msg, Toast.LENGTH_SHORT).show()
    }

}